/**
 * iframe标签简单交互工具
 */
export default class IFrameUtil {
    /**
     * 发送数据
     * @param data
     * @param childrenId -传入id时向iframe子节点传输数据，反之向父级传输数据
     */
    static sendMessage = (data: any, childrenId?: string) => {
        if (childrenId) {
            const iframe = document.getElementById(childrenId) as HTMLIFrameElement
            iframe?.contentWindow?.postMessage(data, '*')
        } else {
            window.parent?.postMessage(data)
        }
    }

    /**
     * 注册接收数据
     * @param fun
     */
    static onMassage = (fun: (data: any) => void) => {
        window.addEventListener('message', fun)
    }

    /**
     * 销毁接收数据
     * @param fun
     */
    static offMassage = (fun: (data: any) => void) => {
        window.removeEventListener('message', fun)
    }
}
